/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.jctc.els.modules.biz.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jctc.els.modules.biz.entity.Role;
import org.jctc.els.modules.biz.entity.User2;
import org.jctc.els.modules.biz.excel.UserExcel;
import org.jctc.els.modules.biz.service.IRoleService;
import org.jctc.els.modules.biz.service.IUserService;
import org.jctc.els.modules.biz.vo.UserVO;
import org.jctc.els.modules.biz.wrapper.UserWrapper;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;
import static org.springblade.core.secure.utils.AuthUtil.getUser;

/**
 * 控制器
 *
 * @author Chill
 */
@NonDS
@ApiIgnore
@RestController
@RequestMapping(AppConstant.APPLICATION_USER_NAME)
@AllArgsConstructor
@MultipartConfig
public class UserController2 {

	private final IUserService userService;

	private final IRoleService roleService;

	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/detail")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<UserVO> detail(User2 user) {
		User2 detail = userService.getOne(Condition.getQueryWrapper(user));
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/info")
	public R<UserVO> info(BladeUser user) {
		User2 detail = userService.getById(user.getUserId());
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> list(@ApiIgnore @RequestParam Map<String, Object> user, Query query, BladeUser bladeUser) {
		QueryWrapper<User2> queryWrapper = Condition.getQueryWrapper(user, User2.class);
		IPage<User2> pages = userService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(User2::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 自定义用户列表
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "列表", notes = "传入account和realName")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> page(@ApiIgnore Query query,
								 @RequestParam(value = "account",required = false) String account,
								 @RequestParam(value = "status",required = false) String status,
								 @RequestParam(value = "deptId",required = false) Long deptId) {
		BladeUser bladeUser = getUser();
		User2 user = new User2();
		IPage<User2> pages = userService.selectUserPage(Condition.getPage(query),account,status,deptId,0L);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiLog("新增或修改用户信息")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增或修改", notes = "传入User")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R submit(@Valid @RequestBody User2 user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.submit(user));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiLog("修改用户信息")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入User")
	public R update(@Valid @RequestBody User2 user) {
		user.setAccount(null);
		String roleId = user.getRoleId();
		List<Role> list = roleService.list(Wrappers.<Role>lambdaQuery().in(Role::getId, Func.toLongList(roleId)));
		String roleAlias = list.get(0).getRoleAlias();
		if(roleAlias.equals("default_admin")){
			return R.data(false);
		}else {
			CacheUtil.clear(USER_CACHE);
			boolean b = userService.updateUser(user);
			return R.data(b);
		}

	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiLog("删除用户信息")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "删除", notes = "传入id集合")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R remove(@RequestParam String ids) {
		QueryWrapper<User2> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", Func.toLong(ids));
		User2 detail = userService.getOne(queryWrapper);
		List<Role> list = roleService.list(Wrappers.<Role>lambdaQuery().in(Role::getId, detail.getRoleId()));
		String roleAlias = list.get(0).getRoleAlias();
		if(roleAlias.equals("default_admin")){
			return R.data(false);
		}else if (roleAlias.equals("administrator")){
			return R.data(false);
		}else {
			CacheUtil.clear(USER_CACHE);
			boolean b = userService.removeUser(ids);
			return R.data(b);
		}

	}

	/**
	 * 设置菜单权限
	 */
	@PostMapping("/grant")
	@ApiLog("设置菜单权限")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "权限设置", notes = "传入roleId集合以及menuId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R grant(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds,
				   @ApiParam(value = "roleId集合", required = true) @RequestParam String roleIds) {
		boolean temp = userService.grant(userIds, roleIds);
		return R.status(temp);
	}

	/**
	 * 重置密码
	 */
	@PostMapping("/reset-password")
	@ApiLog("重置密码")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "初始化密码", notes = "传入userId集合")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R resetPassword(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds) {
		boolean temp = userService.resetPassword(userIds);
		return R.status(temp);
	}

	/**
	 * 修改密码
	 */
	@PostMapping("/update-password")
	@ApiOperationSupport(order = 9)
	@ApiLog("修改密码")
	@ApiOperation(value = "修改密码", notes = "传入密码")
	public R updatePassword(BladeUser user, @ApiParam(value = "旧密码", required = true) @RequestParam String oldPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword1) {
		boolean temp = userService.updatePassword(user.getUserId(), oldPassword, newPassword, newPassword1);
		return R.status(temp);
	}

	/**
	 * 修改基本信息
	 */
	@PostMapping("/update-info")
	@ApiLog("修改基本信息")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "修改基本信息", notes = "传入User")
	public R updateInfo(@Valid @RequestBody User2 user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUserInfo(user));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/user-list")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "用户列表", notes = "传入user")
	public R<List<User2>> userList(User2 user, BladeUser bladeUser) {
		QueryWrapper<User2> queryWrapper = Condition.getQueryWrapper(user);
		List<User2> list = userService.list((!AuthUtil.isAdministrator()) ? queryWrapper.lambda().eq(User2::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(list);
	}

	/**
	 * 导入用户
	 */
	@PostMapping("import-user")
	@ApiLog("导入用户信息")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导入用户", notes = "传入excel")
	public R importUser(HttpServletRequest request) {
		R result = new R();
		String fileName = "";
		//创建一个“硬盘文件条目工厂”对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
		factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
		//设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
		factory.setRepository(new File("/usr/local/games/jars/sts-api"));
		//创建核心对象
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		//设置最大可支持的文件大小（10MB）
		fileUpload.setFileSizeMax(1024 * 1024 * 10);
		//设置转换时使用的字符集
		fileUpload.setHeaderEncoding("UTF-8");
		Long trainingClassesId=null;
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				List<FileItem> fileItems = fileUpload.parseRequest(request);
				for (FileItem fileItem : fileItems) {
					if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
						//获取字段名
						String fieldName = fileItem.getFieldName();
						//获取字段值，并解决乱码
						String fieldValue = fileItem.getString("UTF-8");
						System.out.println(fieldName + " : " + fieldValue);

					} else {//判断该FileItem为一个文件

						System.out.println("Start to upload file!");
						//获取文件名
						fileName = fileItem.getName();
						System.out.println("fileName : " + fileName);
						//获取文件大小
						long fileSize = fileItem.getSize();
						MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
						userService.importUser(multipartFile, request);
						fileItem.write(new File("/usr/local/games/jars/sts-api/upload" + File.separator + fileName));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-user")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出用户", notes = "传入user")
	public void exportUser(@ApiIgnore @RequestParam Map<String, Object> user, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<User2> queryWrapper = Condition.getQueryWrapper(user, User2.class);
//		queryWrapper.lambda().eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<UserExcel> list = userService.exportUser(queryWrapper);
		ExcelUtil.export(response, "用户数据" + DateUtil.time(), "用户数据表", list, UserExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiLog("导出用户信息的模板")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "用户数据模板", "用户数据表", list, UserExcel.class);
	}


	/**
	 * 第三方注册用户
	 */
	@PostMapping("/register-guest")
	@ApiLog("第三方注册用户")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "第三方注册用户", notes = "传入user")
	public R registerGuest(User2 user, Long oauthId) {
		return R.status(userService.registerGuest(user, oauthId));
	}

	/**
	 * 配置用户平台信息
	 */
	@PostMapping("/update-platform")
	@ApiLog("配置用户平台信息")
	@ApiOperationSupport(order = 16)
	@ApiOperation(value = "配置用户平台信息", notes = "传入user")
	public R updatePlatform(Long userId, Integer userType, String userExt) {
		return R.status(userService.updatePlatform(userId, userType, userExt));
	}

	/**
	 * 查看平台详情
	 */
	@ApiOperationSupport(order = 17)
	@ApiOperation(value = "查看平台详情", notes = "传入id")
	@GetMapping("/platform-detail")
	//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<UserVO> platformDetail(User2 user) {
		return R.data(userService.platformDetail(user));
	}


	/**
	 * 用户列表查询
	 */
	@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "人员姓名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "deptName", value = "部门名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "postName", value = "职位名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "current", value = "当前页数", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "size", value = "每页数量", paramType = "query", dataType = "int")
	})
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "用户列表查询", notes = "用户列表查询")
	@GetMapping("/search/user")
	public R<IPage<UserVO>> userSearch(@ApiIgnore UserVO user, @ApiIgnore Query query) {
		return R.data(userService.selectUserSearch(user, query));
	}

	/**
	 * 根据客户id查询用户信息
	 *
	 * @Param:
	 * @return:
	 * @Author: Ice.Wang
	 * @date: 2022/2/18
	 */
	@GetMapping("/list-customer-user")
	public R<List<User2>> listByCustomer(@RequestParam(value = "customerId",required = false) Long customerId) {
		List<User2> userList = userService.selectCustomerUser(customerId);
		return R.data(userList);
	}

}
